package com.lingjtx.iot.network.handle;

import com.alibaba.fastjson2.JSONObject;
import com.lingjtx.common.core.constant.DeviceOpType;
import com.lingjtx.common.core.constant.MqttAction;
import com.lingjtx.common.core.model.iot.DeviceBaseInfo;
import com.lingjtx.common.redis.service.IRedisService;
import com.lingjtx.iot.network.common.DataCache;
import com.lingjtx.iot.network.db.DeviceTemplate;
import com.lingjtx.iot.network.handle.service.DeviceStatusService;
import com.lingjtx.iot.network.handle.service.OTAService;
import com.lingjtx.iot.network.mapper.mysql.DeviceDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class LingjtxHandler {

    private final MqttDataHandler<DeviceTemplate> tslService;
    private final IRedisService redisService;
    private final DeviceDao deviceDao;
    private final DeviceStatusService deviceStatusService;
    private final OTAService otaService;

    public LingjtxHandler(@Qualifier("tslService") MqttDataHandler<DeviceTemplate> tslService,
                          IRedisService redisService, DeviceDao deviceDao,
                          DeviceStatusService deviceStatusService, OTAService otaService) {
        this.tslService = tslService;
        this.redisService = redisService;
        this.deviceDao = deviceDao;
        this.deviceStatusService = deviceStatusService;
        this.otaService = otaService;
    }

    public void resolve(String version, String productId, String mac, String action, String content) {
        log.debug("进入 LingjtxHandler，数据集为：productId={}, mac={}, action={}, content={}", productId, mac, action, content);

        JSONObject jsonObject;
        try {
            jsonObject = JSONObject.parseObject(content);
        } catch (Exception e) {
            log.warn("内容解析失败: content={}, 错误={}", content, e.getMessage());
            return;
        }

        if (jsonObject == null || jsonObject.isEmpty()) {
            log.warn("JSON 解析结果为空或内容为空: content={}", content);
            return;
        }

        DeviceBaseInfo device = DataCache.getDeviceBaseInfo(productId, mac, redisService, deviceDao);
        if (device == null) {
            log.warn("设备未找到: productId={}, mac={}", productId, mac);
            return;
        }

        MqttAction mqttAction = MqttAction.of(action);
        if (mqttAction == null) {
            log.warn("未知的 MqttAction 类型: action={}", action);
            return;
        }

        device.setVersion(version);
        handleAction(device, mqttAction, jsonObject);
    }

    private void handleAction(DeviceBaseInfo device, MqttAction mqttAction, JSONObject jsonObject) {
        switch (mqttAction) {
            case REPORT_DATA:
                tslService.handle(device, jsonObject, redisService, deviceDao, false);
                break;
            case EVENT:
                tslService.handle(device, jsonObject, redisService, deviceDao, true);
                break;
            case STATUS:
                handleStatus(device, jsonObject);
                break;
            case SWITCH_STATUS:
                handleSwitchStatus(device, jsonObject);
                break;
            case OTA:
                otaService.handle(device, jsonObject, redisService);
                break;
            default:
                log.debug("不支持的操作类型: {}", mqttAction);
                break;
        }
    }

    private void handleStatus(DeviceBaseInfo device, JSONObject jsonObject) {
        String status = jsonObject.getString(MqttAction.STATUS.toString());
        DeviceOpType opType = DeviceOpType.OFFLINE.getValue().equals(status)
                ? DeviceOpType.OFFLINE
                : DeviceOpType.ONLINE;
        deviceStatusService.handle(device, opType, null);
    }

    private void handleSwitchStatus(DeviceBaseInfo device, JSONObject jsonObject) {
        Byte switchState = jsonObject.getByte(DeviceOpType.STA_SWITCH.getValue());
        deviceStatusService.handle(device, DeviceOpType.STA_SWITCH, switchState);
    }
}
